<template>
  <div class="file-uploader">
    <!-- 上传区域 -->
    <a-upload-dragger
      v-if="!disabled"
      name="file"
      :multiple="true"
      :showUploadList="false"
      :beforeUpload="beforeUpload"
      @drop="handleDrop"
    >
      <p class="ant-upload-drag-icon">
        <inbox-outlined />
      </p>
      <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
      <p class="ant-upload-hint">
        支持单个或批量上传。严禁上传公司数据或其他违禁文件。
      </p>
    </a-upload-dragger>

    <!-- 文件列表 -->
    <div class="file-list" v-if="fileList.length > 0">
      <a-list>
        <a-list-item v-for="file in fileList" :key="file.id">
          <a-list-item-meta>
            <template #avatar>
              <file-type-icon :fileType="getFileType(file.fileName)" />
            </template>
            <template #title>
              <div class="file-item-title">
                <span>{{ file.fileName }}</span>
                <span class="file-size">{{ formatFileSize(file.fileSize) }}</span>
              </div>
            </template>
            <template #description>
              <div class="file-item-desc">
                <span>{{ formatDate(file.createTime) }}</span>
              </div>
            </template>
          </a-list-item-meta>
          <template #actions>
            <a-button type="link" @click="handlePreview(file)">预览</a-button>
            <a-button type="link" @click="handleDownload(file)">下载</a-button>
            <a-popconfirm
              v-if="!disabled"
              title="确定删除该文件吗?"
              @confirm="handleDelete(file)"
              okText="确定"
              cancelText="取消"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </template>
        </a-list-item>
      </a-list>
    </div>

    <!-- 上传进度 -->
    <div v-if="uploadingFiles.length > 0" class="upload-progress">
      <a-list>
        <a-list-item v-for="(file, index) in uploadingFiles" :key="index">
          <a-list-item-meta>
            <template #title>{{ file.name }}</template>
            <template #description>
              <a-progress :percent="file.percent" size="small" />
            </template>
          </a-list-item-meta>
          <template #actions>
            <a-button 
              v-if="file.status === 'uploading'" 
              type="link" 
              @click="cancelUpload(file)"
              danger
            >
              取消
            </a-button>
            <a-tag v-if="file.status === 'success'" color="success">上传成功</a-tag>
            <a-tag v-if="file.status === 'error'" color="error">上传失败</a-tag>
          </template>
        </a-list-item>
      </a-list>
    </div>

    <!-- 文件预览模态框 -->
    <a-modal
      v-model:visible="previewVisible"
      :title="currentPreviewFile?.fileName || '文件预览'"
      :footer="null"
      :width="800"
      @cancel="previewVisible = false"
    >
      <div class="file-preview-content">
        <!-- 图片预览 -->
        <img
          v-if="isImage(currentPreviewFile?.fileName)"
          :src="getFileUrl(currentPreviewFile)"
          alt="预览图片"
          style="max-width: 100%;"
        />
        
        <!-- PDF预览 -->
        <iframe
          v-else-if="isPDF(currentPreviewFile?.fileName)"
          :src="getFileUrl(currentPreviewFile)"
          style="width: 100%; height: 500px;"
          frameborder="0"
        ></iframe>
        
        <!-- 视频预览 -->
        <video
          v-else-if="isVideo(currentPreviewFile?.fileName)"
          controls
          style="max-width: 100%;"
        >
          <source :src="getFileUrl(currentPreviewFile)" :type="getVideoType(currentPreviewFile?.fileName)" />
          您的浏览器不支持视频播放
        </video>
        
        <!-- 音频预览 -->
        <audio
          v-else-if="isAudio(currentPreviewFile?.fileName)"
          controls
          style="width: 100%;"
        >
          <source :src="getFileUrl(currentPreviewFile)" :type="getAudioType(currentPreviewFile?.fileName)" />
          您的浏览器不支持音频播放
        </audio>
        
        <!-- 其他文件类型 -->
        <div v-else class="other-file-preview">
          <file-type-icon :fileType="getFileType(currentPreviewFile?.fileName)" :size="64" />
          <p>{{ currentPreviewFile?.fileName }}</p>
          <a-button type="primary" @click="handleDownload(currentPreviewFile)">下载文件</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, defineProps, defineEmits, watch, onMounted } from 'vue';
import { InboxOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { defHttp } from '/@/utils/http/axios';
import dayjs from 'dayjs';
import FileTypeIcon from './FileTypeIcon.vue';
import axios from 'axios';
import { useUserStoreWithOut } from '/@/store/modules/user';
import { getFollowPlanFiles, deleteFile } from '../FollowUp.api';

const props = defineProps({
  followPlanId: { type: String, required: true },
  disabled: { type: Boolean, default: false },
});

const emit = defineEmits(['update:fileList', 'fileUploaded', 'fileDeleted']);

// 文件列表
const fileList = ref<any[]>([]);
// 正在上传的文件
const uploadingFiles = ref<any[]>([]);
// 预览相关
const previewVisible = ref<boolean>(false);
const currentPreviewFile = ref<any>(null);

// 上传取消器集合
const uploadCancelTokens = reactive<Record<string, any>>({});

// 监听followPlanId变化，加载文件列表
watch(() => props.followPlanId, (newVal) => {
  if (newVal) {
    loadFileList();
  }
}, { immediate: true });

// 加载文件列表
async function loadFileList() {
  if (!props.followPlanId) return;
  
  try {
    console.log('加载跟进计划文件列表, followPlanId:', props.followPlanId);
    const result = await getFollowPlanFiles(props.followPlanId);
    console.log('获取到文件列表:', result);
    
    if (result && Array.isArray(result)) {
      fileList.value = result;
      emit('update:fileList', fileList.value);
    }
  } catch (error) {
    console.error('加载文件列表失败:', error);
    message.error('加载文件列表失败');
  }
}

// 上传前检查
function beforeUpload(file: File) {
  // 检查文件大小（10MB）
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('文件必须小于10MB!');
    return false;
  }
  
  // 添加到上传列表
  const uploadingFile = {
    uid: Date.now() + Math.random().toString(36).substring(2),
    name: file.name,
    size: file.size,
    type: file.type,
    percent: 0,
    status: 'uploading',
    file: file
  };
  
  uploadingFiles.value.push(uploadingFile);
  
  // 开始上传
  uploadFile(uploadingFile);
  
  // 阻止默认上传行为
  return false;
}

// 处理拖拽
function handleDrop(e: any) {
  console.log('File dropped', e);
}

// 上传文件
async function uploadFile(uploadingFile: any) {
  if (!props.followPlanId) {
    message.error('请先保存跟进计划');
    return;
  }
  
  // 更新上传状态
  const index = uploadingFiles.value.findIndex(item => item.uid === uploadingFile.uid);
  if (index !== -1) {
    uploadingFiles.value[index].status = 'uploading';
  }
  
  const formData = new FormData();
  formData.append('file', uploadingFile.file);
  formData.append('followPlanId', props.followPlanId);
  
  // 调试信息 - 检查文件对象
  console.log('上传文件对象:', uploadingFile.file);
  console.log('文件名:', uploadingFile.file.name);
  console.log('文件大小:', uploadingFile.file.size);
  console.log('文件类型:', uploadingFile.file.type);
  console.log('跟进计划ID:', props.followPlanId);
  
  try {
    // 使用原生XMLHttpRequest上传，方便调试
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      
      // 设置进度回调
      xhr.upload.onprogress = (e) => {
        if (e.lengthComputable) {
          const percent = Math.round((e.loaded * 100) / e.total);
          console.log('上传进度:', percent + '%');
          const index = uploadingFiles.value.findIndex(item => item.uid === uploadingFile.uid);
          if (index !== -1) {
            uploadingFiles.value[index].percent = percent;
          }
        }
      };
      
      // 设置完成回调
      xhr.onload = () => {
        if (xhr.status >= 200 && xhr.status < 300) {
          console.log('上传成功，状态码:', xhr.status);
          console.log('响应内容:', xhr.responseText);
          
          try {
            const result = JSON.parse(xhr.responseText);
            console.log('解析后的响应:', result);
            
            // 上传成功
            const index = uploadingFiles.value.findIndex(item => item.uid === uploadingFile.uid);
            if (index !== -1) {
              uploadingFiles.value[index].status = 'success';
              uploadingFiles.value[index].percent = 100;
              
              // 3秒后移除
              setTimeout(() => {
                uploadingFiles.value = uploadingFiles.value.filter(item => item.uid !== uploadingFile.uid);
              }, 3000);
            }
            
            // 删除取消令牌
            delete uploadCancelTokens[uploadingFile.uid];
            
            // 显示上传成功提示
            const successMessage = result.message || '文件上传成功';
            message.success({
              content: successMessage,
              key: 'upload-success',
              duration: 2
            });
            
            // 刷新文件列表
            loadFileList();
            
            // 触发上传成功事件
            const fileData = result.result || result;
            emit('fileUploaded', fileData);
            
            resolve(result);
          } catch (e) {
            console.error('解析响应失败:', e);
            reject(new Error('解析响应失败'));
          }
        } else {
          console.error('上传失败，状态码:', xhr.status);
          console.error('错误响应:', xhr.responseText);
          
          // 更新状态
          const index = uploadingFiles.value.findIndex(item => item.uid === uploadingFile.uid);
          if (index !== -1) {
            uploadingFiles.value[index].status = 'error';
          }
          
          message.error(`文件上传失败: HTTP ${xhr.status}`);
          reject(new Error(`HTTP错误: ${xhr.status}`));
        }
      };
      
      // 设置错误回调
      xhr.onerror = (e) => {
        console.error('上传错误:', e);
        
        // 更新状态
        const index = uploadingFiles.value.findIndex(item => item.uid === uploadingFile.uid);
        if (index !== -1) {
          uploadingFiles.value[index].status = 'error';
        }
        
        message.error('文件上传失败: 网络错误');
        reject(new Error('网络错误'));
      };
      
      // 获取完整URL - 使用新的API接口
      const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
      const url = `${baseUrl}/followup/followUp/uploadFollowPlanFile`;
      console.log('上传URL:', url);
      
      // 打开连接
      xhr.open('POST', url, true);
      
      // 添加认证头
      const userStore = useUserStoreWithOut();
      const token = userStore.getToken;
      console.log('使用的token:', token);
      if (token) {
        xhr.setRequestHeader('X-Access-Token', token);
      }
      
      // 发送请求
      xhr.send(formData);
    });
  } catch (error: any) {
    console.error('文件上传失败，错误详情:', error);
    
    if (axios.isCancel(error)) {
      console.log('上传已取消');
    } else {
      console.error('文件上传失败:', error);
      message.error(`文件上传失败: ${error.message || '未知错误'}`);
      
      // 更新状态
      const index = uploadingFiles.value.findIndex(item => item.uid === uploadingFile.uid);
      if (index !== -1) {
        uploadingFiles.value[index].status = 'error';
      }
    }
  }
}

// 取消上传
function cancelUpload(file: any) {
  const cancelToken = uploadCancelTokens[file.uid];
  if (cancelToken) {
    cancelToken.cancel('用户取消上传');
    delete uploadCancelTokens[file.uid];
    
    // 从列表中移除
    uploadingFiles.value = uploadingFiles.value.filter(item => item.uid !== file.uid);
  }
}

// 预览文件
function handlePreview(file: any) {
  currentPreviewFile.value = file;
  previewVisible.value = true;
}

// 下载文件
function handleDownload(file: any) {
  if (!file || !file.id) return;
  
  const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
  const url = `${baseUrl}/followup/followUp/downloadFile?fileId=${file.id}`;
  
  const a = document.createElement('a');
  a.href = url;
  a.download = file.fileName || '未命名文件';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

// 删除文件
async function handleDelete(file: any) {
  try {
    if (!file.id) {
      message.error('文件ID不能为空');
      return;
    }
    
    // 使用defHttp.delete直接调用，确保fileId作为query参数传递
    await defHttp.delete({
      url: '/followup/followUp/deleteFile',
      params: { fileId: file.id }
    });
    
    // 从列表中移除
    fileList.value = fileList.value.filter(item => item.id !== file.id);
    emit('update:fileList', fileList.value);
    emit('fileDeleted', file);
    
    message.success('文件删除成功');
  } catch (error: any) {
    console.error('文件删除失败，错误详情:', error);
    message.error(`文件删除失败: ${error.message || '未知错误'}`);
  }
}

// 获取文件URL
function getFileUrl(file: any) {
  if (!file || !file.id) return '';
  
  const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
  return `${baseUrl}/followup/followUp/previewFile?fileId=${file.id}`;
}

// 格式化文件大小
function formatFileSize(size: number) {
  if (!size) return '0 B';
  
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let index = 0;
  let fileSize = size;
  
  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024;
    index++;
  }
  
  return `${fileSize.toFixed(2)} ${units[index]}`;
}

// 格式化日期
function formatDate(date: string) {
  if (!date) return '';
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}

// 获取文件类型
function getFileType(fileName: string) {
  if (!fileName) return 'unknown';
  
  const extension = fileName.split('.').pop()?.toLowerCase() || '';
  
  if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension)) {
    return 'image';
  } else if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm'].includes(extension)) {
    return 'video';
  } else if (['mp3', 'wav', 'ogg', 'flac', 'aac'].includes(extension)) {
    return 'audio';
  } else if (extension === 'pdf') {
    return 'pdf';
  } else if (['doc', 'docx'].includes(extension)) {
    return 'word';
  } else if (['xls', 'xlsx'].includes(extension)) {
    return 'excel';
  } else if (['ppt', 'pptx'].includes(extension)) {
    return 'ppt';
  } else if (['zip', 'rar', '7z'].includes(extension)) {
    return 'archive';
  } else if (['txt', 'log', 'md'].includes(extension)) {
    return 'text';
  } else {
    return 'file';
  }
}

// 判断是否为图片
function isImage(fileName: string) {
  if (!fileName) return false;
  const extension = fileName.split('.').pop()?.toLowerCase() || '';
  return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension);
}

// 判断是否为PDF
function isPDF(fileName: string) {
  if (!fileName) return false;
  const extension = fileName.split('.').pop()?.toLowerCase() || '';
  return extension === 'pdf';
}

// 判断是否为视频
function isVideo(fileName: string) {
  if (!fileName) return false;
  const extension = fileName.split('.').pop()?.toLowerCase() || '';
  return ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm'].includes(extension);
}

// 判断是否为音频
function isAudio(fileName: string) {
  if (!fileName) return false;
  const extension = fileName.split('.').pop()?.toLowerCase() || '';
  return ['mp3', 'wav', 'ogg', 'flac', 'aac'].includes(extension);
}

// 获取视频类型
function getVideoType(fileName: string) {
  if (!fileName) return '';
  const extension = fileName.split('.').pop()?.toLowerCase() || '';
  return `video/${extension}`;
}

// 获取音频类型
function getAudioType(fileName: string) {
  if (!fileName) return '';
  const extension = fileName.split('.').pop()?.toLowerCase() || '';
  return `audio/${extension}`;
}

// 初始化
onMounted(() => {
  if (props.followPlanId) {
    loadFileList();
  }
});
</script>

<style lang="less" scoped>
.file-uploader {
  margin-bottom: 20px;
  
  .file-list {
    margin-top: 16px;
    
    .file-item-title {
      display: flex;
      justify-content: space-between;
      
      .file-size {
        color: rgba(0, 0, 0, 0.45);
        font-size: 12px;
      }
    }
  }
  
  .upload-progress {
    margin-top: 16px;
  }
  
  .file-preview-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    
    .other-file-preview {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 16px;
      padding: 20px;
    }
  }
}
</style> 